﻿using System;
using System.Collections.Generic;
using System.Text;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace UnitOfWorkEF.SqlServer.Domain
{
    class DefaultUnitWorkDbContext : UnitOfWorkDbContext
    {
        private readonly IServiceProvider _serviceProvider;
        protected DefaultUnitWorkDbContext(DbContextOptions options, IMediator mediator, IServiceProvider serviceProvider) : base(options, mediator) => _serviceProvider = serviceProvider;
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            try
            {
                var configurations = _serviceProvider.GetRequiredService<IEnumerable<IEntityTypeConfiguration<Entity>>>();
                foreach (var configuratin in configurations)
                {
                    modelBuilder.ApplyConfiguration(configuratin);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"未获取到EF实体配置,请检查{typeof(IEnumerable<IEntityTypeConfiguration<Entity>>).Name}是否注入", ex);
            }
        }
    }
}
